<script setup>
import { onMounted, ref } from "vue"
import { getUserListPage, batchDeleteUser } from "@/api/user"
import { Delete, Edit } from '@element-plus/icons-vue'
import addUserView from "./addUser.vue"
import { ElMessage, ElMessageBox } from 'element-plus'
const tableData = ref([])
const queryForm = ref({
  nickName: '',
  gender: '',
  status: ''
})
//下拉选择框的选择项
const statusOptions = ref([
  { value: 1, label: "启用" },
  { value: 0, label: "停用" }
])
const genderOptions = ref([
  { value: 1, label: "男" },
  { value: 0, label: "女" }
])
// 分页
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const handleSizeChange = (val) => {
  currentPage.value = 1
  pageSize.value = val
  getAllUser()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAllUser()
}
const getAllUser = async () => {
  let result = await getUserListPage(queryForm.value.nickName, queryForm.value.gender, queryForm.value.status, currentPage.value, pageSize.value)
  tableData.value = result.data.rows
  total.value = result.data.total
}
const cancle = () => {
  queryForm.value = {
    nickName: '',
    gender: '',
    status: ''
  }
  getAllUser()
}
const addView = ref('addView')
const add = () => {
  addView.value.title = '添加用户：'
  addView.value.dialogVisible = true
}

//修改
const handleEdit = async (row) => {
  addView.value.title = '修改用户：'
  addView.value.userForm = JSON.parse(JSON.stringify(row))
  addView.value.dialogVisible = true
}
//过滤管理员不能被删除
// 定义可选择性函数 多选管理员不能被选择
const selectable = (row, index) => {
  // 禁止选择管理员账户
  return row.userName !== 'admin'
}
// 定义受保护的用户
const protectedUsers = ['admin']

const userIds = ref([])
const nickName = ref([])
//删除
const handleSelectionChange = (selection) => {
  userIds.value = selection.map(item => item.userId)
  nickName.value = selection.map(item => item.nickName)
}
const deleteByIds = () => {
  ElMessageBox.confirm('确定要删除姓名为: ' + nickName.value + '的员工吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let result = await batchDeleteUser(userIds.value)
    if (result.code == 200) {
      ElMessage.success('删除成功！')
      getAllUser()
    } else {
      ElMessage.success('删除失败！')
      getAllUser()
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
//单个删除员工
const handleDelete = async (row) => {
  // console.log("删除", row);
  // 检查是否为受保护用户
  if (protectedUsers.includes(row.userName)) {
    ElMessage.warning('该用户为系统保护账户，不能删除！')
    return
  }
  userIds.value = row.userId
  nickName.value = row.nickName
  deleteByIds()
}
onMounted(() => {
  getAllUser()
})
</script>
<template>
  <h2>用户列表</h2>
  <!-- 搜索栏 -->
  <el-form :inline="true" ref="refForm" :model="queryForm" label-width="100px">
    <el-form-item label="用户昵称：" style="width: 230px;">
      <el-input v-model="queryForm.nickName" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item label="性别：" style="width: 200px;">
      <el-select v-model="queryForm.gender" placeholder="请选择" clearable>
        <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="状态：" style="width: 200px;">
      <el-select v-model="queryForm.status" placeholder="请选择" clearable>
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getAllUser">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="default" @click="cancle">清空</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="add"> + 新增用户</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
    </el-form-item>
  </el-form>
  <!-- 表格 -->
  <div>
    <el-table border :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column fixed="left" :selectable="selectable" type="selection" width="55" align="center" />
      <el-table-column type="index" prop="userId" label="用户Id" width="120" align="center" />
      <el-table-column prop="userName" label="用户账号" width="120" align="center" />
      <el-table-column prop="nickName" label="用户昵称" width="120" align="center" />
      <el-table-column prop="avatar" label="头像" width="120" align="center">
        <template #default="scope">
          <img :src="scope.row.avatar" width="50px" height="50px" />
        </template>
      </el-table-column>
      <el-table-column prop="userRole" label="角色" width="120" align="center" />
      <el-table-column prop="gender" label="性别" width="120" align="center">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.gender == 1">男</el-tag>
          <el-tag type="danger" v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120" align="center" />
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.status == 1">启用</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="120" align="center" />
      <el-table-column fixed="right" label="操作" min-width="120" align="center">
        <template #default="scope">
          <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.row)" />
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <br />
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" background=true @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
  <!-- 添加组件 -->
  <addUserView ref="addView" @search="getAllUser" />
</template>
<style scoped></style>